package com.zengqingfa.odd;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @fileName: PrintOddEven2
 * @author: zengqingfa
 * @date: 2022/12/14 17:39
 * @description:
 */
public class PrintOddEven2 {

    public static int count;

    public static ReentrantLock lock = new ReentrantLock();

    static Condition condition1 = lock.newCondition();
    static Condition condition2 = lock.newCondition();


    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    lock.lock();
                    try {
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + "：" + count++);
                            condition2.signalAll();
                        } else {
                            condition1.await();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "偶数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    lock.lock();
                    try {
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + "：" + count++);
                            condition1.signalAll();
                        } else {
                            condition2.await();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }
        }, "奇数线程").start();
    }
}
